<?php
/**
 * 标准注入入口，上游直接按照POST+XML的方式进行注入内容
 * 推送的内容格式为
 * array(
 *  'msgid' => '消息全局唯一标识',
 *  'cpid' => '上下游约定的注入来源标识',
 *  'xml' => '注入的元数据及物理文件XML信息'
 * )
 */
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load_np("np_xml2array.class.php");

class import extends \ns_model\message\message_queue
{
    private $str_source_id = '';//上游来源ID
    private $arr_in_params = array();//上游POST数据

    /**
     * 注入消息队列模板
     * @var unknown
     */
    public $arr_in_message = array(
        'base_info' => array(
            'nns_message_time' => '', //上游消息时间  年月日时分秒毫秒
            'nns_message_id' => '',  //上游消息ID
            'nns_cp_id' => '', //上游CP标示
            'nns_message_xml' => '',  //上游原始的信息  可以为字符串 | xml | json 或则存放消息地址
            'nns_message_content' => '',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
            'nns_action' => '', //操作 行为
            'nns_type' => '', //消息 类型
            'nns_name' => '',  //消息名称
            'nns_package_id' => '',  //包ID
            'nns_xmlurlqc' => '', //广州电信悦ME MD5摘要
            'nns_encrypt' => '', //广州电信悦ME 加密串
            'nns_content_number' => '', //xml文件中包含的内容数量
        ), //基本信息（存储于nns_mgtvbk_message表中）
    );

    public function __construct($arr_in_params)
    {
        $arr_dir = explode('|', str_replace(array('/', '\\'), '|', __DIR__));
        $this->str_source_id = array_pop($arr_dir);
        \m_config::get_dc();
        \m_config::write_message_receive_log("-----------消息接收开始-----------", $this->str_source_id);
        \m_config::write_message_receive_log("上游POST数据为：".var_export($arr_in_params,true), $this->str_source_id);
        $this->arr_in_params = $arr_in_params;
    }

    public function import()
    {
        $arr_source_config = \m_config::_get_cp_info($this->str_source_id);
        if ($arr_source_config['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_receive_log("上游接收来源CDS未配置", $this->str_source_id);
            return $this->__return_data('-1', "上游接收来源CDS未配置");
        }
        if (empty($arr_source_config['data_info']))
        {
            \m_config::write_message_receive_log("获取CP[".$this->str_source_id."]信息为空", $this->str_source_id);
            return $this->__return_data('-1', "获取CP[".$this->str_source_id."]信息为空");
        }
        //检查数据
        if(empty($this->arr_in_params))
        {
            \m_config::write_message_receive_log('POST的数据为空', $this->str_source_id);
            return $this->__return_data('-1','POST的数据为空，请检查您注入的内容');
        }
        if(!isset($this->arr_in_params['cpid']) || $this->arr_in_params['cpid'] !== $this->str_source_id)
        {
            \m_config::write_message_receive_log("POST的数据CPID异常，上游注入CPID为[{$this->arr_in_params['cpid']}]，注入平台配置的CPID为[{$this->str_source_id}]", $this->str_source_id);
            return $this->__return_data('-1', "POST的数据CPID异常，请检查您注入的内容,注入平台配置的CPID为[{$this->str_source_id}]");
        }
        if(!isset($this->arr_in_params['msgid']) || empty($this->arr_in_params['msgid']))
        {
            \m_config::write_message_receive_log('POST的数据MSGID为空', $this->str_source_id);
            return $this->__return_data('-1', 'POST的数据MSGID为空，请检查您注入的内容');
        }
        if(!isset($this->arr_in_params['xml']) || empty($this->arr_in_params['xml']))
        {
            \m_config::write_message_receive_log('POST的数据XML为空', $this->str_source_id);
            return $this->__return_data('-1', 'POST的数据XML为空，请检查您注入的内容');
        }

        //解析XML获取类型
        $this->parse_xml($this->arr_in_params['xml']);

        //组装消息入库信息
        list ( $usec, $sec ) = explode ( ' ', microtime () );
        $time = str_pad(intval(substr($usec, 2, 4)),4,'0',STR_PAD_LEFT);
        $micro_time = date('YmdHis', time()) . $time;
        $this->arr_in_message['base_info']['nns_message_time'] = $micro_time;
        $this->arr_in_message['base_info']['nns_message_id'] = $this->arr_in_params['msgid'];
        $this->arr_in_message['base_info']['nns_cp_id'] = $this->str_source_id;
        $this->arr_in_message['base_info']['nns_message_content'] = $this->arr_in_params['xml'];

        //入库消息队列
        $result_message = $this->push($this->arr_in_message);
        if($result_message['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_receive_log("入库消息失败:".var_export($result_message,true)."入库内容为：".var_export($this->arr_in_message,true), $this->str_source_id);
            return $this->__return_data('-1', '上游消息入库失败,请联系注入平台运维人员！');
        }
        return $this->__return_data(0, "成功");
    }
    /**
     * 获取媒资类型与操作类型
     * @param $contents
     */
    private function parse_xml($contents)
    {
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($contents);
        $xml = $dom->saveXML();
        $xml_arr = np_xml2array::getArrayData($xml);//ret 0失败  1成功
        if ($xml_arr["ret"] != NS_CDS_FAIL)
        {
            \m_config::write_message_receive_log("解析得到的XML工单错误",$this->str_source_id);
            return;
        }
        foreach ($xml_arr['data']['children'] as $v)
        {
            if ($v['name'] == 'Objects')
            {
                $objects = $v['children'];
                continue;
            }
        }
        //取其中一个object作为type
        switch ($objects[0]['attributes']['ElementType'])
        {
            case 'Series':
                $this->arr_in_message['base_info']['nns_type'] = 4;
                break;
            case 'Program':
                $this->arr_in_message['base_info']['nns_type'] = 5;
                break;
            case 'Movie':
                $this->arr_in_message['base_info']['nns_type'] = 6;
                break;
        }

        switch ($objects[0]['attributes']['Action'])
        {
            case 'DELETE':
                $this->arr_in_message['base_info']['nns_action'] = 3;
                break;
            default:
                $this->arr_in_message['base_info']['nns_action'] = 1;
                break;
        }
        return;
    }
    /**
     * 接收消息反馈
     * @param $ret
     * @param $reason
     * @return string
     */
    private function __return_data($ret, $reason)
    {
        $dom = new DOMDocument('1.0', 'utf-8');
        $xml_header = "<result/>";
        $dom->loadXML($xml_header);
        $dom->firstChild->setAttribute('ret', $ret);
        $dom->firstChild->setAttribute('reason', $reason);
        return $dom->saveXML();
    }
}

$import = new import($_POST);
echo $import->import();